package com.ruoyi.project.tool.swagger.UserController;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.utils.ImageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.aspectj.lang.annotation.SignatureValidation;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;

import com.ruoyi.framework.security.service.SysLoginService;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysAddress;
import com.ruoyi.project.system.domain.SysMobileUser;
import com.ruoyi.project.system.domain.vo.UserInfo;
import com.ruoyi.project.system.domain.vo.WxLoginInfo;
import com.ruoyi.project.system.service.ISysAddressService;
import com.ruoyi.project.system.service.ISysMobileUserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mobileUser/user/")
@Validated
public class UserMobileController extends BaseController {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private ISysMobileUserService sysMobileUserService;

    @Autowired
    private ISysAddressService sysAddressService;

    @Autowired
    private SysLoginService loginService;



    // 用户信息修改 暂时为:头像用户名
    @RepeatSubmit
    @SignatureValidation
    @PostMapping("updateMobileUser")
    public AjaxResult queryMyService(@RequestBody SysMobileUser sysMobileUser) {
        return AjaxResult.success(sysMobileUserService.updateSysMobileUser(sysMobileUser));
    }

    /**
     * 查询所有的用户列表
     */
    @SignatureValidation
    @GetMapping("/list")
    public TableDataInfo list(SysMobileUser sysMobileUser) {
        Long mobileUserId = SecurityUtils.getLoginUser().getSysMobileUser().getMobileUserId();
        sysMobileUser.setMobileUserId(mobileUserId);
        List<SysAddress> sysAddresses = sysAddressService.selectSysAddressAllList(mobileUserId);
        startPage();
        List<SysMobileUser> list = sysMobileUserService.selectSysMobileUserList(sysMobileUser);
        for (int i = 0; i < list.size(); i++) {
            SysMobileUser user = list.get(i);
            user.setSysAddresses(sysAddresses);
        }
        return getDataTable(list);
    }

    /**
     * 微信授权登录
     */
    @SignatureValidation
    @PostMapping("authorizedLogin")
    public AjaxResult insertMobileUser(@RequestBody WxLoginInfo wxLoginInfo) {
        Map map = new HashMap();
        String path = "F:\\ruoyi\\"+ IdUtil.simpleUUID()+".jpg";
        String code = wxLoginInfo.getCode();
        UserInfo userInfo = wxLoginInfo.getUserInfo();
        if("".equals(code) || null == userInfo){
            return AjaxResult.error("参数不正确");
        }
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxMaService.getUserService().getSessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sessionKey == null || openId == null) {
            return AjaxResult.error("错误");
        }
        SysMobileUser sysMobileUser = sysMobileUserService.queryUserOpenId(openId);
        if(null == sysMobileUser){
            sysMobileUser = new SysMobileUser();
            sysMobileUser.setUserName(openId);
            sysMobileUser.setOpenId(openId);
            sysMobileUser.setPassword(SecurityUtils.encryptPassword(openId));
            sysMobileUser.setStatus("0");
            sysMobileUser.setDelFlag("0");
            sysMobileUser.setSex(userInfo.getGender());
            String avatarUrl = ImageUtils.downloadPicture(userInfo.getAvatarUrl(), path);
            sysMobileUser.setAvatar(avatarUrl);
            sysMobileUserService.insertSysMobileUser(sysMobileUser);
//          UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysMobileUser.getUserName(), openId);
          String token = loginService.loginMobile(sysMobileUser.getUserName(),openId);
            map.put("token",token);
            map.put("userInfo",userInfo);
            return AjaxResult.success(map);
        }else{
            return AjaxResult.error("不可重复授权");
        }
    }


    /**
     * 查询所有的用户列表
     */
    @SignatureValidation
    @PostMapping("/getAll")
    public AjaxResult getAll(@RequestBody SysMobileUser sysMobileUser) {
        Object token = loginService.loginMobile(sysMobileUser.getUserName(),sysMobileUser.getPassword());
        return AjaxResult.success(token);
    }
}
